package com.chengxiaoxiao.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class AllCharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig;

    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) resp;
        } catch (Exception e) {
            throw new ServletException("No Http request or response");
        }

        String encoding = filterConfig.getInitParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }

        //POST请求
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);

        //GET
        MyServletRequest myRequest = new MyServletRequest(request);

        chain.doFilter(myRequest, response);

    }


    public void destroy() {
    }


}

class MyServletRequest extends HttpServletRequestWrapper {

    public MyServletRequest(HttpServletRequest request) {
        super(request);
    }


    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (value == null) {
            return null;
        }

        if ("get".equalsIgnoreCase(super.getMethod())) {
            try {

                byte[] bytes = value.getBytes("ISO-8859-1");
                value = new String(bytes, super.getCharacterEncoding());

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return value;

    }
}